<?php
namespace Org\Util;
class JSSDK {
	private $appId;
	private $appSecret;
	/**
	 * 构造
	 */
	public function __construct() {
		$this -> appId = C('APPID');
		$this -> appSecret = C('APPSECRET');
	}

	/**
	 * code作为换取access_token的票据，
	 * 每次用户授权带上的code将不一样，
	 * code只能使用一次，5分钟未被使用自动过期。
	 * code换取的是一个特殊的网页授权access_token,
	 * 与基础支持中的access_token（该access_token用于调用其他接口）不同。
	 * @return
	 * {
	 "access_token":"ACCESS_TOKEN",
	 "expires_in":7200,
	 "refresh_token":"REFRESH_TOKEN",
	 "openid":"OPENID",
	 "scope":"SCOPE",
	 "unionid": "o6_bmasdasdsad6_2sgVt7hMZOPfL"
	 }
	 */
	public function get_code_access_token($code) {
		$appId = $this -> appId;
		$appSecret = $this -> appSecret;
		$url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appId&secret=$appSecret&code=$code&grant_type=authorization_code";
		$data = json_decode($this -> httpGet($url));
		$result['access_token'] = $data->access_token;
		$result['expires_in'] = $data->expires_in;
		$result['refresh_token']  = $data->refresh_token;
		$result['openid'] = $data->openid;
		$result['scope'] = $data->scope;
		$result['unionid'] = $data->unionid;
		return $result;
	}
	/**
	 * 刷新access_token
	 */
	public function refresh_token($refresh_token){
		$appId = $this -> appId;
		$url = "https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=$appId&grant_type=refresh_token&refresh_token=$refresh_token";
		$data = json_decode($this -> httpGet($url));		
		$result['access_token'] = $data->access_token;
		$result['expires_in'] = $data->expires_in;
		$result['refresh_token']  = $data->refresh_token;
		$result['openid'] = $data->openid;
		$result['scope'] = $data->scope;
		return $result;		
	}
	/**
	 * 
	 * @param access_token	网页授权接口调用凭证,注意：此access_token与基础支持的access_token不同
	 * @param openid	用户的唯一标识
	 * @param lang	返回国家地区语言版本，zh_CN 简体，zh_TW 繁体，en 英语
	 */
	public function get_userinfo($access_token,$openid,$lang='zh_CN'){
		$url = "https://api.weixin.qq.com/sns/userinfo?access_token=$access_token&openid=$openid&lang=$lang";
		$data = json_decode($this -> httpGet($url));	
		$result['openid'] = $data->openid;
		$result['nickname'] = $data->nickname;
		$result['sex'] = $data->sex;
		$result['city'] = $data->city;
		$result['country'] = $data->country;
		$result['province'] = $data->province;
		$result['language'] = $data->language;
		$result['headimgurl'] = $data->headimgurl;
		$result['subscribe_time'] = $data->subscribe_time;
		$result['unionid'] = $data->unionid;		
		$result['privilege'] = $data->privilege;
		$result['groupid'] = $data->groupid;
		return $result;
	}

	/**
	 * 获取签名
	 */
	public function getSignPackage() {
		$jsapiTicket = $this -> getJsApiTicket();

		// 注意 URL 一定要动态获取，不能 hardcode.
		$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
		$url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
		$timestamp = time();
		$nonceStr = $this -> createNonceStr();

		// 这里参数的顺序要按照 key 值 ASCII 码升序排序
		$string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";

		$signature = sha1($string);
		$signPackage = array(
		//appid这个名称不可以用
		"AppId" => $this -> appId, "nonceStr" => $nonceStr, "timestamp" => $timestamp, "url" => $url, "signature" => $signature, "rawString" => $string);
		return $signPackage;
	}

	/**
	 * 获取NonceStr
	 */
	private function createNonceStr($length = 16) {
		$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
		$str = "";
		for ($i = 0; $i < $length; $i++) {
			$str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
		}
		return $str;
	}

	/**
	 * 获取jsapi_ticket
	 */
	private function getJsApiTicket() {
		//__WEIXIN_CONFIG__
		// jsapi_ticket 应该全局存储与更新，以下代码以写入到文件中做示例
		$data = F('JSAPI_TICKET');
		if ($data['expire_time'] < time()) {
			$accessToken = $this -> getAccessToken();
			// 如果是企业号用以下 URL 获取 ticket
			// $url = "https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token=$accessToken";
			$url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=$accessToken";
			$res = json_decode($this -> httpGet($url));
			$ticket = $res -> ticket;
			if ($ticket) {
				$data['expire_time'] = time() + 7000;
				$data['jsapi_ticket'] = $ticket;
				//修改配置
				F('JSAPI_TICKET', $data);
			}
		} else {
			$ticket = $data['jsapi_ticket'];
		}
		return $ticket;
	}

	/**
	 * 获取access_token
	 */
	private function getAccessToken() {
		// access_token 应该全局存储与更新，以下代码以写入到文件中做示例
		$data = F('ACCESS_TOKEN');
		if ($data['expire_time'] < time()) {
			// 如果是企业号用以下URL获取access_token
			// $url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=$this->appId&corpsecret=$this->appSecret";
			$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$this->appId&secret=$this->appSecret";
			$res = json_decode($this -> httpGet($url));
			$access_token = $res -> access_token;
			if ($access_token) {
				$data['expire_time'] = time() + 7000;
				$data['access_token'] = $access_token;
				F('ACCESS_TOKEN', $data);
			}
		} else {
			$access_token = $data['access_token'];
		}
		return $access_token;
	}

	/**
	 * GET请求
	 */
	private function httpGet($url) {
		$curl = curl_init();
		curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($curl, CURLOPT_TIMEOUT, 500);
		curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
		curl_setopt($curl, CURLOPT_URL, $url);

		$res = curl_exec($curl);
		curl_close($curl);

		return $res;
	}
	/**
	 * 获取snsapi_userinfo方式url
	 */
	public function get_snsapi_userinfo_url($state='mp_jeekup'){
		$appid = C('AppID');
		$redirect_uri = C('WEIXIN_REDIRECT_URI_INFO');
		return "https://open.weixin.qq.com/connect/oauth2/authorize?appid=$appid&redirect_uri=$redirect_uri&response_type=code&scope=snsapi_userinfo&state=$state#wechat_redirect";
	}
	/**
	 * 获取snsapi_base方式url
	 */
	public function get_snsapi_base_url($state='mp_jeekup'){
		$appid = C('AppID');
		$redirect_uri = C('WEIXIN_REDIRECT_URI_BASE');
		return "https://open.weixin.qq.com/connect/oauth2/authorize?appid=$appid&redirect_uri=$redirect_uri&response_type=code&scope=snsapi_base&state=$state#wechat_redirect";
	}	

}
